import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
import pathlib


class XEMail(object):

    @staticmethod
    def send(p_sender, p_password, p_to, p_title, p_content, p_mail_host='smtp.baosight.com', p_port=25,
             p_attachments=None):
        '''
        发送邮件函数，默认使用163smtp
        :param p_sender: 邮箱账号 xx@163.com
        :param p_password: 邮箱密码
        :param p_to: 邮箱接收人地址，多个账号以逗号隔开
        :param p_title: 邮件标题
        :param p_content: 邮件内容
        :param p_mail_host: 邮箱服务器
        :param p_port: 端口号
        :param p_attachments: 多个附件，存放在list内
        :return:
        '''
        if p_attachments:
            msg = MIMEMultipart()
            part_text = MIMEText(p_content)
            msg.attach(part_text)
            for f in p_attachments:
                tmp_attach = MIMEApplication(open(file=f, mode='rb').read())
                tmp_attach.add_header('Content-Disposition', 'attachment', filename=pathlib.Path(f).name)
                msg.attach(tmp_attach)
        else:
            msg = MIMEText(p_content)
        msg['Subject'] = p_title
        msg['From'] = p_sender
        msg['To'] = p_to
        smtp = smtplib.SMTP(p_mail_host, port=p_port)
        smtp.login(p_sender, p_password)
        smtp.sendmail(p_sender, p_to.split(','), msg.as_string())
        smtp.quit()


if __name__ == '__main__':
    send_address = "sshc625@163.com"
    send_password = 'QWYCRIMOCSWNBRAR'
    receivers = '89090125@qq.com'
    title = "这是一封测试邮件"
    content = "Hi，你好！这封邮件是python发送的"
    # attachfilepath = "D:\课设文件\文档\尝试.xls"
    # send_mail(p_user=send_address, p_password=send_password, p_to=receivers, p_title=title, p_content=content, p_attachment=attachfilepath)
    XEMail.send(p_sender=send_address, p_password=send_password, p_to=receivers, p_title=title, p_content=content)
    print('success')
